import React, { JSX } from 'react';
import dicomParser from 'dicom-parser';
import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader/dist/cornerstoneWADOImageLoaderNoWebWorkers.bundle.min';
import cornerstone from 'cornerstone-core';
import { Box, BoxProps } from '@mui/material';
import { v4 as uuidv4 } from 'uuid';

interface DicomProps extends BoxProps {
  data?: ArrayBuffer;
};

function DicomViewer(props: DicomProps): JSX.Element {
  const { data } = props;

  const [file, setFile] = React.useState<File | undefined>(undefined);

  React.useEffect(() => {
    if (data !== undefined) {
      const blob = new Blob([data]);
      const nfile = new File([blob], uuidv4());
      setFile(nfile);
    }
  }, [data]);

  return (
    <DicomFileViewer {...{...props, data: undefined, file: file}} />
  );
}

interface DicomFileProps extends BoxProps {
  file?: File;
};

function DicomFileViewer(props: DicomFileProps): JSX.Element {
  const { file } = props;

  const elementRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
    cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
    cornerstoneWADOImageLoader.webWorkerManager.initialize({
      webWorkerPath: '/static/dist/cornerstoneWADOImageLoaderWebWorker.js',
      taskConfiguration: {
        decodeTask: {
          initializeCodecsOnStartup: true,
        },
      },
    });
  });

  React.useEffect(() => {
    if (file !== undefined) {
      cornerstone.enable(elementRef.current);
      const imageId = cornerstoneWADOImageLoader.wadouri.fileManager.add(file);
      cornerstone.loadImage(imageId).then((image: any) => {
        const viewport = cornerstone.getDefaultViewportForImage(elementRef.current, image);
        cornerstone.displayImage(elementRef.current, image, viewport);
      });
    }
  }, [file]);

  return (
    <Box {...{ ...props, file: undefined }}>
      <Box ref={elementRef} sx={{ width: '100%', height: '100%' }} />
    </Box>
  );
}

export { DicomViewer, DicomFileViewer };